<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\Stamp;
use App\Services\StampService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class StampController extends Controller
{
    protected $StampService;
    public function __construct(StampService $StampService)
    {
        $this->StampService = $StampService;
    }

    public function index(Request $Request) {
        $limit = $Request->limit ?: 10;
        $page = $Request->page ?: 1;
        $page = $page * $limit - $limit;
        
        $sql = $this->StampService->get();
        $sql->where('user_id',Auth::user()->id);
        $total = $sql->count();
        $data = $sql->skip($page)->take($limit)->orderBy('created_at','desc')->get();
        return response()->json(['code' => '200', 'msg' => '操作成功','total'=>$total,'data'=>$data]);
    }

    public function show(Request $Request) {
        $data = Stamp::with('project')->with('user')->with('handled')->where('id',$Request->id)->first();
        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data]);
    }

    /**
     * 存储一个新数据。
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $Request)
    {
        $POSTONLY = Stamp::POSTONLY;
        $input = $Request->only($POSTONLY);
        $input['user_id'] = Auth::user()->id;
        $data = $this->StampService->insert($input);
        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data]);
    }


    public function update(Request $Request)
    {
        if(!$Request->id){
            return response()->json(['code' => '404', 'msg' => '请选择要操作的记录']);
        }

        $POSTONLY = Stamp::POSTONLY;
        $input = $Request->only($POSTONLY);
        $input['id'] = $Request->id;
        $data = $this->StampService->update($input);
        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data]);
    }

    public function delete(Request $Request)
    {
        if(!$Request->id){
            return response()->json(['code' => '404', 'msg' => '请选择要操作的记录']);
        }
        $data = Stamp::find($Request->id);
        $data->delete();
        return response()->json(['code' => '200', 'msg' => '操作成功']);
    }
}
